# _*_ coding:utf-8 _*_
# @Time  : 2023.03.25
# @Author: zizlee


import sys
import MySQLdb
from MySQLdb.converters import conversions
from MySQLdb.constants import FIELD_TYPE
from dbutils.pooled_db import PooledDB


work_db_params = {
    "host": "localhost",
    "port": 3306,
    "user": "root",
    "password": "mysql",
    "database": "ruizhi"
}

local_db_params = {
    "host": "localhost",
    "port": 3306,
    "user": "root",
    "password": "mysql",
    "database": "company_exchange_data"
}


def get_converters():
    conversions[FIELD_TYPE.BIT] = lambda x: 1 if int.from_bytes(x, byteorder=sys.byteorder, signed=False) else 0
    return conversions


def db_conn_pool():
    return PooledDB(
        creator=MySQLdb, mincached=5, maxcached=10,
        conv=get_converters(), charset='utf8mb4',
        blocking=True,
        **work_db_params
    )


def local_db_pool():
    return PooledDB(
        creator=MySQLdb, mincached=5, maxcached=10,
        conv=get_converters(), charset='utf8mb4',
        blocking=True,
        **local_db_params
    )


class DataBaseConnection(object):
    def __init__(self):
        self.conn = db_conn_pool().connection()  # 从连接池取得一个连接
        self.cursor = self.conn.cursor(MySQLdb.cursors.DictCursor)  # 连接的游标

    def begin(self):
        self.conn.begin()

    def close(self):
        self.cursor.close()
        self.conn.close()

    def commit(self):
        self.conn.commit()

    def rollback(self):
        self.conn.rollback()

    def __enter__(self):
        self.begin()
        return self.cursor

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type:
            self.rollback()
            print(f'MySQL Error:{ exc_type.__name__ }:{ exc_val }')
        else:
            self.commit()
        self.close()


class LocalDataBase(object):
    def __init__(self):
        self.conn = local_db_pool().connection()  # 从连接池取得一个连接
        self.cursor = self.conn.cursor(MySQLdb.cursors.DictCursor)  # 连接的游标

    def begin(self):
        self.conn.begin()

    def close(self):
        self.cursor.close()
        self.conn.close()

    def commit(self):
        self.conn.commit()

    def rollback(self):
        self.conn.rollback()

    def __enter__(self):
        self.begin()
        return self.cursor

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type:
            self.rollback()
            print(f'LOCAL MySQL Error:{ exc_type.__name__ }:{ exc_val }')
        else:
            self.commit()
        self.close()
